package com.briup.homework.chap12;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Test03_Server {
    public static void main(String[] args) throws Exception {
        int port = 8002;
        //1.搭建TCP服务器
        ServerSocket serverSocket = new ServerSocket(port);
        //2.接收客户端的连接
        Socket accept = serverSocket.accept();
        //3.读取客户端传递的Teacher集合并遍历
        // 3.1 获取输入流并封装成对象流
        ObjectInputStream ois = new ObjectInputStream(accept.getInputStream());
        // 3.2 读取集合对象并遍历
        Object o = ois.readObject();
        List<Teacher> teachers = new ArrayList<>();
        if(o instanceof List<?> list){
            for(Object obj:list){
                if(obj instanceof Teacher teacher){
                    teachers.add(teacher);
                }
            }
        }
        //4.将集合对象(含所有老师信息)写入本地文件t.txt，txt文件位置 src/t.txt
        // 4.1 定义文件输出流并封装成对象流
        FileOutputStream fos = new FileOutputStream("src/t.txt");
        // 4.2 向t.txt文件中写入数据
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(teachers);
        //5.返回响应信息给客户端
        // 5.1 获取输出流并封装成缓冲流
        BufferedWriter bw = new BufferedWriter(
                new OutputStreamWriter(
                        accept.getOutputStream()));
        // 5.2 返回ok信息给客户端
        bw.write("ok");
        //6.关闭资源
        bw.close();
        oos.close();
        fos.close();
        accept.close();
        serverSocket.close();
    }
}
